#include "common.hpp"


uint16_t server_port;
std::string server_ip;
int socket_fd;

int main(int argc, char* argv[])
{
    //./client_TCP [server_port] [server_ip]  
    if(argc != 3)
    {
        std::cout << "usage: " << argv[0] << " [server_port] [server_ip]" << std::endl;
        exit(USAGE_ERR);
    }

    server_port = static_cast<uint16_t>(std::stoi(argv[1]));
    server_ip = argv[2];

    //1.创建socket
    //不像服务端得到的是listen_socket_fd, 客户端socket得到的是直接可以进行IO的socket_fd 
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);//前两个参数组合代表TCP协议通信
    if(socket_fd < 0)
    {
        LOG(wzx::log_level::FATAL) << "socket construct failed!!!";
        exit(SOCKFD_CON_ERR);
    }
    LOG(wzx::log_level::INFO) << "socket construct successfully, _socket_fd: " << socket_fd;

    //2.connect
    Inet_Addr server(server_port, server_ip);
    int ret_connect = connect(socket_fd, (const sockaddr*)(&server.get_addr()), sizeof(server.get_addr()));
    if(ret_connect < 0)
    {
        LOG(wzx::log_level::FATAL) << "connect failed!!!";
        exit(CONNECT_ERR);
    }
    LOG(wzx::log_level::INFO) << "connect successfully, _socket_fd: " << socket_fd;


    //3.通信
    bool success_tag = true;
    while(true)
    {
        std::string inbuffer;
        std::cout << "please enter:> ";
        std::getline(std::cin, inbuffer);

        ssize_t in_count = write(socket_fd, inbuffer.c_str(), inbuffer.size());
        if(in_count > 0)//写入(发消息)成功了
        {
            char outbuffer[1024];
            ssize_t out_count = read(socket_fd, outbuffer, sizeof(outbuffer) - 1 /*留一个'\0'的位置*/);
            if(out_count > 0)//读(收消息)成功了
            {
                outbuffer[out_count] = '\0'; //字符串末尾加'\0', 防止访问越界
                std::cout << "server reply:> " << outbuffer << std::endl;
            }
            else
            {
                success_tag = false;
                break;
            }
        }
        else
        {
            success_tag = false;
            break;
        }
    }

    if(success_tag = false)
    {
        LOG(wzx::log_level::FATAL) << "communication failed!!!";
        exit(COMMUNICATION_ERR);
    }

    return 0;
}